const supportPageOffset = window.pageXOffset !== undefined;
const isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");

//触发刷新的高度
const offset = 90;

const touch = {
    data:{
        y:0,
        el:'',
    },
    touchStar(e){
        if(STATUS.loading || !STATUS.isTop()){
            return false;
        }
        touch.data.y = e.touches[0].pageY;
        //currentTarget有时获取不了
        // touch.el = e.currentTarget;
      
    },
    touchMove(e){
        if(STATUS.loading || !STATUS.isTop()){
            return false;
        }
        e.preventDefault();
        e.stopPropagation();
        let curY = e.touches[0].pageY,
            movY = touch.data.y - curY,
            direction;
        if(movY > 0){
            direction = 'up'
        }else if(movY < 0){
            direction = 'down'
        }

        let absY = Math.abs(movY);
        touch.move(absY,0)
        
        if(absY >=70){
            STATUS.loading = true;
            setTimeout(function(){
                STATUS.loading = false; 
                touch.touchEnd();
            },5000)
            return false;

        }
    },
    touchEnd:function(e){
        touch.data.y = 0;
        if(!STATUS.loading) touch.move(0);
        
    },
    move(y,time = 300){
        touch.data.el.style="position: relative; overflow: visible; transition-property: transform; transition-timing-function: ease-out; transition-duration: "+time+"ms; transform: translate3d(0px, "+y+"px, 0px);"
       time == 30 && setTimeout(function(){
            touch.data.el.style = ''
        },300)
    }
}

const STATUS = {
    loading:false,
    isTop(){
        return STATUS.scrollY() == 0;
    },
    scrollY(){
        return supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;;
    }
}

export default {
    name:"pullfresh",
    bind(el,binding){
    },
    inserted(el,binding){
        
        touch.data.el = el;
        el.addEventListener('touchstart',touch.touchStar)
        el.addEventListener('touchmove',touch.touchMove)
        el.addEventListener('touchend',touch.touchEnd)
        el.addEventListener('touchcancel',touch.touchEnd)
    },
    update(){
    },
    componentUpdated(){
    },
    unbind(el){
        el.removeEventListener('touchstart',touch.touchStar)
        el.removeEventListener('touchmove',touch.touchMove)
        el.removeEventListener('touchend',touch.touchEnd)
        el.removeEventListener('touchcancel',touch.touchEnd)
    }
}
